//
//  AppDelegate.m
//  HEARME
//
//  Created by liujinhui on 16/1/21.
//  Copyright (c) 2016年 dllo. All rights reserved.
//

#import "AppDelegate.h"
#import "LJHDisAllViewController.h"
#import "LJHCusAllViewController.h"
#import "LJHCateViewController.h"
#import "LJHMineViewController.h"
#import "LJHBaseNavigationController.h"
#import <AVFoundation/AVFoundation.h>
#import "LJHGuideViewController.h"

@interface AppDelegate ()
@property( nonatomic,retain) LJHTabBarViewController *tabbar;
@property( nonatomic,retain) LJHDisAllViewController *disVC;
@property( nonatomic,retain) LJHBaseNavigationController *disNa;
@end

@implementation AppDelegate

-(void)dealloc
{
    [_allImageView release];
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"db426a9829e4b49a0dcac7b4162da6b6" url:@"http://www.umeng.com/social"];
    
    [SMSSDK registerApp:@"f3ebaacdd480" withSecret:@"6ed762114feef54bc0a448a621bafb64"];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *tabState = [user objectForKey:@"state"];
    
    if (tabState == nil) {
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"state"];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    self.disVC = [[LJHDisAllViewController alloc]init];
    self.disNa = [[LJHBaseNavigationController alloc]initWithRootViewController:self.disVC];
    self.disNa.navigationBar.translucent = NO;

    LJHCusAllViewController *cusVC = [[LJHCusAllViewController alloc]init];
    LJHBaseNavigationController *cusNa = [[LJHBaseNavigationController alloc]initWithRootViewController:cusVC];
 
    LJHCateViewController *cateVC = [[LJHCateViewController alloc]init];
    LJHBaseNavigationController *cateNa = [[LJHBaseNavigationController alloc]initWithRootViewController:cateVC];
  
    LJHMineViewController *mineVC = [[LJHMineViewController alloc]init];
    LJHBaseNavigationController *mineNa = [[LJHBaseNavigationController alloc]initWithRootViewController:mineVC];

    self.tabbar = [[LJHTabBarViewController alloc]init];
    LJHPlayerViewController *playVc = [[LJHPlayerViewController alloc]init];
    self.tabbar.viewControllers = @[self.disNa,cateNa,playVc,cusNa,mineNa];
    self.tabbar.tabBar.alpha = 1;
    self.tabbar.tabBar.translucent = NO;
    self.tabbar.tabBar.tintColor = [UIColor redColor];
    self.window.rootViewController = self.tabbar;
    
//    [playNa release];
    [self.window release];
    [_disVC release];
    [_disNa release];
    [cusVC release];
    [cusNa release];
    [cateVC release];
    [cateNa release];
    [mineVC release];
    [mineNa release];
    
    NSString *leadInPagesState = [user objectForKey:@"LeadInPages"];
    
    if ([leadInPagesState isEqualToString:@"yes"]) {
        
        self.window.rootViewController = self.tabbar;
        
    }
    else {
    
        LJHGuideViewController *guideVC = [[LJHGuideViewController alloc]init];
        
        self.window.rootViewController = guideVC;
    }
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LeadInPages) name:@"LeadInPages" object:nil];
    

    [[LJHFMData shareFMDB]openDB];
    [[LJHFMData shareFMDB]openDBandCreate];
    
    NSError* error;
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outputDeviceChanged:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    
    
    [self isHeadsetPluggedIn];

    
    // Override point for customization after application launch.
    return YES;
}

//友盟集成
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}


//换引导页
- (void)LeadInPages {
    
    self.window.rootViewController = self.tabbar;
    
    
}
- (void)outputDeviceChanged:(NSNotification *)aNotification
{
    
    NSDictionary *userInfoDic = [aNotification userInfo];
    
    AVAudioSessionRouteDescription *dic = [userInfoDic objectForKey:@"AVAudioSessionRouteChangePreviousRouteKey"];
    for (AVAudioSessionPortDescription* desc in [dic outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones]) {
            
            LJHPlayerViewController *player = [LJHPlayerViewController sharaMusicPlayer];
            
            [player playButtonAction:nil];
            
        }
        
    }
    
    
}
//iOS检测耳机是否插入(单纯的判断开始的时候,是否存在耳机)
- (BOOL)isHeadsetPluggedIn {
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
            return YES;
    }
    return NO;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    //
    //    NSLog(@"\n\n倔强的打出一行字告诉你我要挂起了。。\n\n");
    if ([LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePlaying||[LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStateBuffering||[LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePaused ||[LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStateStopped) {
        //有音乐播放时，才给后台权限，不做流氓应用。
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
        
        [application beginBackgroundTaskWithExpirationHandler:nil];
        
    } else {
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        [self resignFirstResponder];
        
        [application endBackgroundTask:UIBackgroundTaskInvalid];
    }
}


//后台控制
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    
    NSLog(@">>>>>会走吗>>>>>");
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        LJHPlayerViewController *player = [LJHPlayerViewController sharaMusicPlayer];
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlPause:
                //点击了暂停
                [player playButtonAction:nil];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                //点击了下一首
                [player nextButtonAction:nil];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                //点击了上一首
                [player upButtonAction:nil];
                //此时需要更改歌曲信息
                break;
            case UIEventSubtypeRemoteControlPlay:
                //点击了播放
                [player playButtonAction:nil];
                break;
            default:
                break;
        }
    }
}



- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
